package com.ruoyi.MtTakeaway.config;

import com.ruoyi.common.utils.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import static java.util.Formatter.Conversion.CHARACTER;


/**
 * @Description: TODO
 * @Author zhangguangyan
 * @Date 2023/09/24/ 21:00:48
 */
public class MtGetSign {
    public static String generateSignature(Map<String, String> params, String secretKey) {
        // 第一步：参数排序
        Set<String> keySet = params.keySet();
        String[] keys = keySet.toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        for (String key : keys) {
            if ("sign".equals(key)) {
                continue;
            }
            // 参数为空不参与签名
            String value = params.get(key);
            if (StringUtils.isNotEmpty(value)) {
                query.append(key).append(value);
            }
        }

        // 第三步：使用hmac加密
        byte[] bytes = encryptHMAC(query.toString(), secretKey);

        // 第四步：把二进制转化为大写的十六进制(正确签名应该为32大写字符串)
        return byte2hex(bytes);
    }

    public static byte[] encryptHMAC(String data, String secret) {
        byte[] bytes = null;
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(CHARACTER), "HmacMD5");
            Mac mac = Mac.getInstance(secretKeySpec.getAlgorithm());
            mac.init(secretKeySpec);
            bytes = mac.doFinal(data.getBytes(CHARACTER));
        } catch (Exception e) {
            throw new ArithmeticException(e.toString());
        }
        return bytes;
    }

    public static String byte2hex(byte[] bytes) {
        StringBuffer sign = new StringBuffer(bytes.length * 2);
        for (int n = 0; n < bytes.length; n++) {
            String tmp = (java.lang.Integer.toHexString(bytes[n] & 0XFF));
            if (tmp.length() == 1) {
                sign.append("0");
            }
            sign.append(tmp);
        }
        return sign.toString().toUpperCase();
    }
}
